// 账号
const loginIdValidator = new FieldValidator("txtLoginId", async function (val) {
  if (!val) {
    return "账号不能为空";
  }
  const resp = await API.exists(val);
  if (resp.data) {
    return "该账号已被注册，请重新更换账号名";
  } else {
    return "账号可以注册";
  }
});

// 昵称
const txtNicknameValidator = new FieldValidator("txtNickname", function (val) {
  if (!val) {
    return "昵称不能为空";
  }
});

// 密码
const txtLoginPwdValidator = new FieldValidator("txtLoginPwd", function (val) {
  if (!val) {
    return "密码不能为空";
  }
});

// 二次密码
const txtLoginPwdConfirmValidator = new FieldValidator(
  "txtLoginPwdConfirm",
  function (val) {
    if (!val) {
      return "确认密码不能为空";
    }
    if (val !== txtLoginPwdValidator.input.value) {
      return "两次密码不一致";
    }
  }
);

const form = $(".user-form");
form.onsubmit = async function (e) {
  e.preventDefault(); //阻止浏览器默认跳转
  // 判断输入框规则是否正确
  const result = FieldValidator.validate(
    loginIdValidator,
    txtNicknameValidator,
    txtLoginPwdValidator,
    txtLoginPwdConfirmValidator
  );
  if (!result) {
    return; //验证未通过
  }
  const formData = new FormData(form);
  const data = Object.fromEntries(formData.entries());

  // 网络注册
  const resp = await API.reg(data);
  if (resp.c === 0) {
    alert("注册成功，点击确定，跳转到登录页");
    location.href = "./login.html";
  }
};
